package controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import biz.MissionBiz;
import pojo.Missions;
import pojo.Projects;

/** 
* @author WuYuan
* 
*/
@Controller
public class MissionController {
	@Resource(name="missionBiz")
	private MissionBiz missionBiz;
	
	@RequestMapping("findMissionsByUrpid.do")
	public String findMissionsByUrpid(String projectId, String userId,String roleId,HttpServletRequest  request){
		System.out.println("获取projectId="+projectId+" userId="+userId+" roleId="+roleId);
		List<Missions> missionslist = missionBiz.findMissionsByUrpid(projectId ,userId,roleId);
		System.out.println(missionslist.get(0).toString());
		request.setAttribute("missionslist", missionslist);
		return "missionlist";
	}
	
	@RequestMapping("findMissionsRelationship.do")
	public void findMissionsRelationship(String projectId, HttpServletRequest  request,HttpServletResponse response ){
		System.out.println("findMissionsRelationship层获得的信息是"+projectId);
		BufferedImage image=missionBiz.findMissionRelationByUrpid(projectId, "2");
		 try {if(image!=null){
			ImageIO.write(image, "JPEG", response.getOutputStream());
			response.getOutputStream().flush();
			image.flush();
			}else{
				PrintWriter out=response.getWriter();
				out.println("1");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	        
	}
	
	@ResponseBody
	@RequestMapping("CompleteMission.do")
	public String completeMission(String missionid){
		System.out.println(missionid);
		int iscompleted =missionBiz.updateCompleteMission(missionid);
		if(iscompleted==1){
			return 1+"";
		}else
		return 0+"";
	}
	
	@ResponseBody
	@RequestMapping("findProjectsByUrpid.do")
	public void findProjectsByUserid(String teamId, String userId,HttpServletResponse response){
		response.setCharacterEncoding("utf-8");
		PrintWriter out=null;
		ObjectMapper mapper=new ObjectMapper();
		List<Projects> projectsList = missionBiz.findProjectsByUrpid(teamId, userId);
//		System.out.println(projectsList.get(0).getProjectName());
		try {
			out=response.getWriter();
			out.println(mapper.writeValueAsString(projectsList));
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
